package com.xiaozhen.blog.service.impl;

import com.xiaozhen.blog.service.LikeService;
import com.xiaozhen.blog.utils.RedisCache;
import com.xiaozhen.blog.utils.RedisKeyUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

/**
 * @create 2023-05-16 14:09
 */
@Service
public class LikeServiceImpl implements LikeService {

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 点赞
     *
     * @param entityType
     * @param userId
     * @param entityId
     */
    public void like(int userId, int entityType, Long entityId) {
        String entityLikeKey = RedisKeyUtils.getEntityLikeKey(entityType, entityId);
        Boolean isMember = redisTemplate.opsForSet().isMember(entityLikeKey, userId);
        System.out.println("没有执行吗" + isMember);
        if (isMember) {
            // 如果已经点过赞了,则从 redis 中将数据删除
            redisTemplate.opsForSet().remove(entityLikeKey, userId);
            System.out.println("执行了删除？？");
        } else {
            // 如果没点过赞,则添加数据到 redis 中
            redisTemplate.opsForSet().add(entityLikeKey, userId);
            System.out.println("执行了添加？？");
        }
    }

    /**
     * 查询某实体（博客、评论）点赞的数量
     *
     * @param entityType
     * @param entityId 实体 Id(博客 id、评论 id)
     * @return
     */
    public long findEntityLikeCount(int entityType, Long entityId) {
        String entityLikeKey = RedisKeyUtils.getEntityLikeKey(entityType, entityId);
        Long size = redisTemplate.opsForSet().size(entityLikeKey);
        System.out.println("点赞数量？？" + size);
        return redisTemplate.opsForSet().size(entityLikeKey);
    }

    /**
     * 查询某人对某实体的点赞状态
     * @param userId
     * @param entityType
     * @param entityId
     * @return
     */
    public int findEntityLikeStatus(Long userId,int entityType, Long entityId){
        String entityLikeKey = RedisKeyUtils.getEntityLikeKey(entityType, entityId);
        //  1（已点赞） 0（赞）
        int status = redisTemplate.opsForSet().isMember(entityLikeKey, userId)?1:0;
        System.out.println("返回状态");
        return status;
    }

}
